package com.caipos.akka;

import akka.actor.AbstractActor;
import akka.actor.ActorRef;
import akka.actor.Props;
import com.caipos.entity.Device;
import com.caipos.entity.DeviceData;
import com.caipos.service.DeviceService;
import lombok.AllArgsConstructor;
import lombok.Getter;

import java.time.LocalDateTime;

/**
 * 设备管理器Actor，负责设备注册和状态管理
 */
public class DeviceManagerActor extends AbstractActor {

    // 注入设备服务（在构造函数中获取，确保Spring上下文已就绪）
    private final DeviceService deviceService;
    // 数据处理Actor引用
    private final ActorRef dataProcessingActor;

    /**
     * 构造函数，通过SpringContextHolder获取服务
     */
    public DeviceManagerActor(ActorRef dataProcessingActor) {
        this.dataProcessingActor = dataProcessingActor;
        // 此时Spring上下文已通过ContextRefreshedEvent确保初始化完成
        this.deviceService = SpringContextHolder.getBean(DeviceService.class);
    }

    /**
     * 创建Props（Actor的创建工厂）
     */
    public static Props props(ActorRef dataProcessingActor) {
        return Props.create(DeviceManagerActor.class, () -> new DeviceManagerActor(dataProcessingActor));
    }

    /**
     * 消息处理逻辑
     */
    @Override
    public Receive createReceive() {
        return receiveBuilder()
                .match(RegisterDeviceMessage.class, this::handleRegisterDevice)
                .match(DeviceDataMessage.class, this::handleDeviceData)
                .match(DeviceHeartbeatMessage.class, this::handleHeartbeat)
                .build();
    }

    /**
     * 处理设备注册消息
     */
    private void handleRegisterDevice(RegisterDeviceMessage message) {
        if (!deviceService.deviceExists(message.getDeviceId())) {
            Device device = new Device();
            device.setDeviceId(message.getDeviceId());
            device.setDeviceName(message.getDeviceName());
            device.setDeviceType(message.getDeviceType());
            device.setIpAddress(message.getIpAddress());
            device.setPort(message.getPort());
            device.setStatus("ONLINE");
            device.setRegisterTime(LocalDateTime.now());
            device.setLastHeartbeat(LocalDateTime.now());

            deviceService.registerDevice(device);
        } else {
            // 设备已存在，更新状态
            deviceService.updateDeviceStatus(message.getDeviceId(), "ONLINE");
//            deviceService.updateDeviceLastHeartbeat(message.getDeviceId(), LocalDateTime.now());
        }
    }

    /**
     * 处理设备数据，转发给数据处理Actor
     */
    private void handleDeviceData(DeviceDataMessage message) {
        dataProcessingActor.forward(message, getContext());
    }

    /**
     * 处理设备心跳
     */
    private void handleHeartbeat(DeviceHeartbeatMessage message) {
//        deviceService.updateDeviceLastHeartbeat(message.getDeviceId(), LocalDateTime.now());
        deviceService.updateDeviceStatus(message.getDeviceId(), "ONLINE");
    }

    // 消息定义（内部静态类，确保可序列化）
    @Getter
    @AllArgsConstructor
    public static class RegisterDeviceMessage {
        private String deviceId;
        private String deviceName;
        private String deviceType;
        private String ipAddress;
        private int port;
    }

    @Getter
    @AllArgsConstructor
    public static class DeviceDataMessage {
        private DeviceData data;
    }

    @Getter
    @AllArgsConstructor
    public static class DeviceHeartbeatMessage {
        private String deviceId;
    }
}
    